﻿using System;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Web.UI;

namespace OpenWaves.Web.Controls
{
    public class GoogleMap : GoogleMapBase<object>
    {
        public string LongitudeMember { get; set; }
        public string LatitudeMember { get; set; }
        public string ToolTipMember { get; set; }

        protected override double ResolveLongitude(object item)
        {
            Contract.Assert(this.LongitudeMember.IsNullOrWhiteSpace() == false);

            var longitude = DataBinder.Eval(item, this.LongitudeMember);
            Contract.Assert(longitude != null);

            return Convert.ToDouble(longitude, CultureInfo.InvariantCulture);
        }

        protected override double ResolveLatitude(object item)
        {
            Contract.Assert(this.LatitudeMember.IsNullOrWhiteSpace() == false);

            var latitude = DataBinder.Eval(item, this.LatitudeMember);
            Contract.Assert(latitude != null);

            return Convert.ToDouble(latitude, CultureInfo.InvariantCulture);
        }

        protected override string ResolveToolTip(object item)
        {
            if (String.IsNullOrEmpty(this.ToolTipMember))
                return String.Empty;

            var toolTip = DataBinder.Eval(item, this.ToolTipMember);
            if (toolTip == null)
                return String.Empty;

            return toolTip.ToString();
        }

    }

    public abstract class GoogleMap<T> : GoogleMapBase<T>
    {
        private readonly Func<T, double> latitudeResolver;

        private readonly Func<T, double> longitudeResolver;

        private readonly Func<T, string> toolTipResolver;

        protected GoogleMap(Func<T, double> latitudeResolver, Func<T, double> longitudeResolver) 
            : this(latitudeResolver, longitudeResolver, null)
        {}

        protected GoogleMap(Func<T, double> latitudeResolver, Func<T, double> longitudeResolver, Func<T, string> toolTipResolver)
        {
            Contract.Requires<ArgumentNullException>(latitudeResolver != null);
            Contract.Requires<ArgumentNullException>(longitudeResolver != null);

            this.latitudeResolver = latitudeResolver;
            this.longitudeResolver = longitudeResolver;
            this.toolTipResolver = toolTipResolver;
        }

        protected override double ResolveLatitude(T item)
        {
            return this.latitudeResolver(item);
        }

        protected override double ResolveLongitude(T item)
        {
            return this.longitudeResolver(item);
        }

        protected override string ResolveToolTip(T item)
        {
            if (this.toolTipResolver != null)
                return this.toolTipResolver(item);
            return String.Empty;
        }
    }
}